<script setup lang="tsx">
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import { useBoolean } from '@sa/hooks';
import { h, reactive } from 'vue';
import type { Role } from '@/service/api';
import { deleteRoles, fetchGetRoleList, getFetchRoleUrl } from '@/service/api';
import { useAppStore } from '@/store/modules/app';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { $t } from '@/locales';
import { useAuth } from '@/hooks/business/auth';
import SvgIcon from '@/components/custom/svg-icon.vue';
import { DICT_TYPE, getDictObj } from '@/utils/dict';
import RoleOperateModel from './modules/role-operate-model.vue';
import RoleSearch from './modules/role-search.vue';
import MenuAuthModal from './modules/menu-auth-modal.vue';

const appStore = useAppStore();
const { hasAuth } = useAuth();
const { bool: menuAuthVisible, setTrue: openMenuAuthModal } = useBoolean();

const {
  columns,
  columnChecks,
  data,
  loading,
  getData,
  getDataByPage,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchGetRoleList,
  showTotal: true,
  apiParams: {
    current: 1,
    size: 10,
    // if you want to use the searchParams in Form, you need to define the following properties, and the value is null
    // the value can not be undefined, otherwise the property in Form will not be reactive
    status: null,
    keywords: null
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'index',
      title: $t('common.index'),
      width: 64,
      align: 'center'
    },
    {
      key: 'name',
      title: $t('page.manage.role.roleName'),
      align: 'center',
      minWidth: 120
    },
    {
      key: 'type',
      title: $t('page.manage.role.roleType'),
      align: 'center',
      minWidth: 120
    },
    {
      key: 'code',
      title: $t('page.manage.role.roleCode'),
      align: 'center',
      minWidth: 120
    },
    {
      key: 'sort',
      title: $t('page.manage.role.roleSort'),
      align: 'center',
      minWidth: 120
    },
    {
      key: 'remark',
      title: $t('page.manage.role.roleDesc'),
      align: 'center',
      minWidth: 120
    },
    {
      key: 'status',
      title: $t('page.manage.role.roleStatus'),
      align: 'center',
      width: 100,
      render: row => {
        if (row.status === null) {
          return null;
        }

        const dictObj = getDictObj(DICT_TYPE.COMMON_STATUS, row.status);

        return <NTag type={dictObj?.colorType}>{dictObj?.label}</NTag>;
      }
    },
    {
      key: 'createTime',
      title: $t('page.manage.role.createTime'),
      align: 'center',
      minWidth: 120
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 350,
      render: row => (
        <div class="flex-center gap-8px">
          <div v-show={hasAuth('system:role:update')}>
            <NButton type="primary" ghost size="small" onClick={() => edit(row.id)}>
              {{
                default: () => $t('common.edit'),
                icon: () => h(SvgIcon, { icon: 'ep:edit' })
              }}
            </NButton>
          </div>
          <div v-show={hasAuth('system:role:update')}>
            <NButton type="primary" ghost size="small" onClick={() => menuAuthModal(row)}>
              {$t('page.manage.role.menuAuth')}
            </NButton>
          </div>
          <div v-show={hasAuth('system:role:update')}>
            <NButton type="primary" ghost size="small" onClick={() => edit(row.id)}>
              {$t('page.manage.role.dataAuth')}
            </NButton>
          </div>
          <div v-show={hasAuth('system:role:delete')}>
            <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
              {{
                default: () => $t('common.confirmDelete'),
                trigger: () => (
                  <NButton type="error" ghost size="small">
                    {{
                      default: () => $t('common.delete'),
                      icon: () => h(SvgIcon, { icon: 'ep:delete' })
                    }}
                  </NButton>
                )
              }}
            </NPopconfirm>
          </div>
        </div>
      )
    }
  ]
});

const {
  modelVisible,
  operateType,
  editingData,
  handleAdd,
  handleEdit,
  checkedRowKeys,
  onBatchDeleted,
  onDeleted,
  fetchDataUrl
  // closeDrawer
} = useTableOperate(data, getData);

async function handleBatchDelete() {
  // request
  const { error } = await deleteRoles(checkedRowKeys.value.join(','));

  await onBatchDeleted(error);
}

async function handleDelete(id: number) {
  // request
  const { error } = await deleteRoles(id.toString());

  await onDeleted(error);
}

function edit(id: number) {
  fetchDataUrl.value = getFetchRoleUrl(id);
  handleEdit(id);
}

type RoleModel = Pick<Role, 'id' | 'name' | 'code' | 'remark'>;

const model: RoleModel = reactive({
  id: 0,
  name: '',
  code: '',
  remark: ''
});
function menuAuthModal(row: Role) {
  Object.assign(model, row);
  openMenuAuthModal();
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <RoleSearch
      v-if="hasAuth('system:role:query')"
      v-model:model="searchParams"
      @reset="resetSearchParams"
      @search="getDataByPage"
    />
    <NCard :title="$t('page.manage.role.title')" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          create-auth="system:role:create"
          delete-auth="system:role:delete"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @refresh="getData"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="702"
        :loading="loading"
        remote
        :row-key="row => row.id"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <RoleOperateModel
        v-model:visible="modelVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getDataByPage"
      />
    </NCard>
    <MenuAuthModal v-model:visible="menuAuthVisible" :role="model" />
  </div>
</template>

<style scoped></style>
